# coding: utf8
# try something like
def index(): return dict(message="hello from plugin_pdf_datedreports.py")

def report():
   #form for the dates input
   form = SQLFORM.factory(Field('start_date', 'date', 
                                label='Start Date',
                                requires=IS_DATE()),
                          Field('end_date', 'date', 
                                label='End Date',
                                requires=IS_DATE()))
   #form with invisible fields for PDF requesting
   pdf_link = FORM(INPUT(_type='submit', _value='PDF'),
                 hidden=dict(start_date=request.vars.start_date,
                             end_date=request.vars.end_date),
                _action='report.pd')
   #to do the query only one time
   #ask about extension for pdf or valid form data
   if request.extension == 'pd' or form.accepts(request.vars, session):
       #get date objects
       start_date = request.now.strptime(request.vars.data_ini, '%Y-%m-%d')
       end_date = request.now.strptime(request.vars.data_fim, '%Y-%m-%d')
       #the query
       rep = db((db.table.data >= data_ini) & 
                  (db.table.data <= data_fim)).select()
       #html table with the rows and labels from the models
       t_rep = SQLTABLE(rep, headers=dict([('table.' + f, db.table[f].label) for
                                            f in db.table.fields]))
       #if a pdf was requested
       if request.extension == 'pd':
           pdf = Report()
           pdf.add_page()
           #PYFPDF needs width attributs
           #as SQLTABLE don´t do like this, we need a hack
           ths = t_rep.elements('th')
           ths[0]['_width'] = '12%' # column widths
           ths[1]['_width'] = '60%'
           #send html to the pdf with required encoding
           pdf.write_html(t_rep.xml().decode('UTF-8').encode('cp1252'))
           response.headers['Content-Type'] = 'application/pdf'
           #send the PDF as a string
           return pdf.output(dest='S')
       else:
           #displays form for input, the report and a PDF button
          return dict(form=form, rep=rep, pdf_link=pdf_link)
   else:
       #display only the form and a message for input
      return dict(form=form, rep='Pick a date range.', pdf_link=None)
